package cn.chenhuanming.chuanzhi.service;

import cn.chenhuanming.chuanzhi.dao.StaffDao;
import cn.chenhuanming.chuanzhi.util.authority.AuthorityTool;
import cn.chenhuanming.chuanzhi.util.entity.Staff;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.Lock;
import org.springframework.security.crypto.password.StandardPasswordEncoder;
import org.springframework.stereotype.Service;

import javax.persistence.LockModeType;
import java.time.LocalDate;

/**
 * Created by Administrator on 2017-05-06.
 */
@Service
public class StaffService {

    @Autowired
    StaffDao staffDao;

    public Page<Staff> listStaff(String keyword,Pageable pageable){
        return staffDao.findByUsernameContainingOrRealNameContaining(keyword,keyword,pageable);
    }

    public Staff findOne(String username){
        return staffDao.findOne(username);
    }

    @Lock(value = LockModeType.PESSIMISTIC_WRITE)
    public boolean signUp(String username,String password){
        Staff staff = findOne(username);
        if(staff!=null)
            return false;
        else{
            staff = new Staff(username,new StandardPasswordEncoder().encode(password));
            staff.setInTime(LocalDate.now());
            staffDao.save(staff);
            return true;
        }
    }

    public void updateMe(Staff staff){
        Staff staffInDB = staffDao.findOne(AuthorityTool.getPrincipal());
        staffInDB.setRealName(staff.getRealName());
        staffInDB.setSex(staff.getSex());
        staffInDB.setGrade(staff.getGrade());
        staffInDB.setMajor(staff.getMajor());
        staffInDB.setArea(staff.getArea());
        staffInDB.setDepartment(staff.getDepartment());
        staffInDB.setPhone(staff.getPhone());
        staffInDB.setWechat(staff.getWechat());
        staffInDB.setQq(staff.getQq());
        staffInDB.setGithub(staff.getGithub());
        staffInDB.setIsSingle(staff.getIsSingle());
        staffDao.save(staffInDB);
    }

    public boolean changePassword(String oldPassword,String newPassword){
        Staff me = staffDao.findOne(AuthorityTool.getPrincipal());
        if(new StandardPasswordEncoder().matches(oldPassword,me.getPassword())){
            me.setPassword(new StandardPasswordEncoder().encode(newPassword));
            staffDao.save(me);
            return true;
        }
        return false;
    }
}
